<?php
/**
 * Introduction: 店铺表  micro_shop
 */

namespace Common\Model;


use App\Models\MicroShopBonusDetail;
use App\Models\MicroShopBonusExpand;
use App\Models\MicroShopBonusSales;
use App\Models\MicroShopBonusService;
use App\Models\MicroShopBonusTaskCount;
use App\Models\MicroShopBonusTaskExpand;
use App\Models\MicroShopSalesFlow;
use App\Models\OrderProduct;
use Think\Model;
use Think\Wxpay\Wxpush;

class MicroShopModel extends Model
{
    //定义数据库连接信息
    protected $connection;

    //定义表名
    protected $tableName = 'micro_shop';

    /**
     * 初始化
     */
    public function _initialize()
    {

        $this->connection = C('Databaese');

    }

    /**
     * 官方店member_id
     */
    private $officialMemberId = 14441;

    /**
     * 免费升级店铺所需推广店铺数
     * @var array $ruleOfUpgradeShopFree
     */
    private $ruleOfUpgradeShopFree = array(
        '2'=>array(
            'num' =>100//推广吃货数量，达到后可免费升级红人馆
        )
    );

    /**
     * 所有活动的分红规则
     * @var array
     */
    private $bonusRuleOfAll = array(
        // 普通区
        0	=> array(
            '1'=>array(
                'self'     =>0.2,//本店返利百分比
                'direct'   =>0,//直接推荐人获得
                'permit_day'=>7//订单完成多久后可领取红包，单位：天
            ),
            '2'=>array(
                'self'     =>0.1,
                'direct'   =>0,//直接推荐人获得
                'permit_day'=>7//订单完成多久后可领取红包，单位：天
            ),
            '3'=>array(
                'self'     =>0,
                'direct'   =>0,//直接推荐人获得
                'permit_day'=>7//订单完成多久后可领取红包，单位：天
            )
        ),
        // 全返
        1	=> array(
            '1'=>array(
                'self'     =>0.2,//本店返利百分比
                'direct'   =>0,//直接推荐人获得
                'permit_day'=>7//订单完成多久后可领取红包，单位：天
            ),
            '2'=>array(
                'self'     =>0.1,
                'direct'   =>0,//直接推荐人获得
                'permit_day'=>7//订单完成多久后可领取红包，单位：天
            ),
            '3'=>array(
                'self'     =>0,
                'direct'   =>0,//直接推荐人获得
                'permit_day'=>7//订单完成多久后可领取红包，单位：天
            ),
        ),
        // 普通区，全场满99全返
        2	=> array(
            '1'=>array(
                'self'     =>0.2,//本店返利百分比
                'direct'   =>0,//直接推荐人获得
                'permit_day'=>7//订单完成多久后可领取红包，单位：天
            ),
            '2'=>array(
                'self'     =>0.1,
                'direct'   =>0,//直接推荐人获得
                'permit_day'=>7//订单完成多久后可领取红包，单位：天
            ),
            '3'=>array(
                'self'     =>0,
                'direct'   =>0,//直接推荐人获得
                'permit_day'=>7//订单完成多久后可领取红包，单位：天
            ),
        ),
        3	=> array(
            '1'=>array(
                'self'     =>0.2,//本店返利百分比
                'direct'   =>0,//直接推荐人获得
                'permit_day'=>7//订单完成多久后可领取红包，单位：天
            ),
            '2'=>array(
                'self'     =>0.1,
                'direct'   =>0,//直接推荐人获得
                'permit_day'=>7//订单完成多久后可领取红包，单位：天
            ),
            '3'=>array(
                'self'     =>0,
                'direct'   =>0,//直接推荐人获得
                'permit_day'=>7//订单完成多久后可领取红包，单位：天
            )
        )
    );

    /**
     * 产生订单 红包规则
     * @var unknown
     */
    private $bonusRuleOfOrder = array(
        '1'=>array(
            'self'     =>0.2,//本店返利百分比
            'direct'   =>0,//直接推荐人获得
            'permit_day'=>7//订单完成多久后可领取红包，单位：天
        ),
        '2'=>array(
            'self'     =>0.1,
            'direct'   =>0,//直接推荐人获得
            'permit_day'=>7//订单完成多久后可领取红包，单位：天
        ),
        '3'=>array(
            'self'     =>0,
            'direct'   =>0,//直接推荐人获得
            'permit_day'=>7//订单完成多久后可领取红包，单位：天
        ),
    );

    /**
     * 购买套餐开店
     * @var array
     */
    private $bonusRuleOfRecomendingShops = array(
        '2'=>array(
            'direct'=>30,//直接推荐人获得
            'indirect'=>10,//间接推荐人获得
        )
    );

    /**
     * 有支付后的订单更新微店销售额(计算该累计的销售额)
     * @param unknown $orderId
     */
    public function updateSalesInfoByOrder($orderId){
        $model = new OrderModel();
        $orderInfo = $model->where("order_id=$orderId")->field("ms_id,cost,cpns_price,discount,status,order_time,member_id")->find();

        if(!empty($orderInfo) && $orderInfo['ms_id']>0 && $orderInfo['status']>1){//微店已支付的订单才统计
            $cost = $orderInfo['cost'] - $orderInfo['cpns_price']- $orderInfo['discount'];// ;//参与销售额的金额
            $flow_time_str = date('Ym',$orderInfo['order_time']);
            //更新自己
            $this->saveSalesInfo($orderInfo['ms_id'], $flow_time_str, $cost);


            $model = new TarentoModel();
            $shopInfo = $model->where("member=".$orderInfo['ms_id'])->field("relations,level")->find();
            $relations = $shopInfo['relations'];

            if($shopInfo['level']>1){//如果不是顶级则查找所有上级并更新他们的团队销售额
                $othersMid = str_replace(','.$orderInfo['ms_id'].',', '', $relations);
                if(!empty($othersMid)){
                    $members = explode(',', $othersMid);
                    foreach ($members as $memberId)
                    {
                        $this->saveSalesInfo($memberId, $flow_time_str, 0, $cost);//更新所有上级的团队销售额
                    }
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 更新微店销售额(写入或更新数据)
     * @param unknown $memberId
     * @param unknown $flow_time_str
     * @param number $self_sales
     * @param number $group_sales
     */
    private function saveSalesInfo($memberId,$flow_time_str,$self_sales=0,$group_sales=0)
    {
        $model = new MicroShopSalesFlowModel();
        $flowinfo = $model->where("member_id=$memberId and flow_time_str='$flow_time_str'  and status=0")->field("id,self_sales,group_sales")->find();
        $flowId = $flowinfo['id'];
        if($flowId>0){//已经有该月的数据则更新
            $data['self_sales'] = $flowinfo['self_sales']+$self_sales;
            $data['group_sales'] = $flowinfo['group_sales']+$group_sales;
            $model->where("id=$flowId")->save($data);
        }else{//无则新增
            $data1['member_id'] = $memberId;
            $data1['self_sales'] = $self_sales;
            $data1['group_sales'] = $group_sales;
            $data1['status'] = 0;
            $data1['flow_time_str'] = $flow_time_str;
            $model->add($data1);
        }

        return true;
    }


    /**
     * 微店订单发红包---销售红包
     * @param unknown $orderId
     * @param unknown $ignoreStatus 忽略订单状态
     * @param unknown $selfCost 订单金额，如果传入这个参数则以传入的金额作为返利基数
     */
    public function giveOutBonusOfOrder($orderId,$ignoreStatus=false,$selfCost=0)
    {
        $or_model = new OrderModel();
        $orderInfo = $or_model->where("order_id=$orderId")->field("member_id,ms_id,cost,cpns_price,discount,ms_discount,status,finished_time")->find();

        //查询当前购买产品ID
        $p_model = new OrderProductModel();
        $ret_order_product = $p_model->where("order_id=$orderId")->select();
        $productIDS = array();
        $productCommonIDS = array();
        $productActiveIDS = array();
// 		$active_id = 0;

        foreach ($ret_order_product as $item_product) {
            $productIDS[] = $item_product['product_id'];
        }

        // TODO: test
        $productIDS_json = json_encode($productIDS);
        $orderLogModel = new OrderLogModel();
        $orderLog_data['order_id'] = $orderId;
        $orderLog_data['admin_id'] = 0;
        $orderLog_data['admin_name'] = '';
        $orderLog_data['text'] = "product_id:$productIDS_json";
        $orderLog_data['behavior'] = "test";
        $orderLog_data['result'] = "success";
        $orderLogModel->add($orderLog_data);

        //查询该用户累积消费金额
        $re = $or_model->where("pay_status='2' and status='2' and member_id=".$orderInfo['member_id'])->field("cost")->select();

        $allCost = 0;
        foreach($re as $vos){
            $allCost += $vos['cost'];
        }
        //查询当前用户等级
        $ta_model = new TarentoModel();
        $userlevel = $ta_model->where("member_id=".$orderInfo['member_id'])->field("level")->find();

        $userlevel = $userlevel['level'];

        if(!empty($orderInfo) && $orderInfo['ms_id']>0){//微店已支付的订单发红包
            if($orderInfo['status']!=2 && !$ignoreStatus){
                return false;
            }
            $isSelfCostOrder = ($selfCost>0 && $ignoreStatus) ? true : false;//是否是自定义返利基数，补发红包的订单
            if ($isSelfCostOrder) {
                $cost = $selfCost;
            } else {
                $cost = $orderInfo['cost'] - $orderInfo['cpns_price']  + $orderInfo['ms_discount'];//参与返利的初始金额 - $orderInfo['discount']
                $cost = $cost <= 0 ? 1 : $cost;
            }

            $shopInfo = $ta_model->alias('a')->join("left join haiou_micro_shop as b on a.member_id=b.member_id")->where("a.member_id=".$orderInfo['ms_id'])->field("a.direct_rec_mid,a.indirect_rec_mid,a.relations,a.level,b.name")->find();

            if(!empty($shopInfo)){
                $shopLevel = $shopInfo['level'] > 3 ? 3 : $shopInfo['level'];
                $allRule = $this->bonusRuleOfOrder;
                $rule = $this->bonusRuleOfOrder[$shopLevel];

                if($userlevel == 3){
                    //如果购买199套餐产品或者累积金额大于1000且该用户身份为吃货.系统则自动升级该吃货为红人馆
                    if(in_array(31679, $productIDS) || in_array(31680, $productIDS) || in_array(32146, $productIDS) || in_array(32145, $productIDS) || in_array(32144, $productIDS) || in_array(32143, $productIDS) || in_array(32142, $productIDS) || in_array(31951, $productIDS) || in_array(31950, $productIDS) || in_array(31949, $productIDS) || $allCost >= 1000){
                        //升级店铺
                        $this->upgrade_shop($orderInfo['member_id'], 2,$orderId);
                    }
                }

                // 计算各种奖励，根据购买的产品类型
                $bonusList = $this->calculateKindsOfBonus($orderInfo, $ret_order_product, $shopLevel);

// TODO: test
                $bonusListStr = $this->arr2equation($bonusList);
                $orderLogModel->add(['order_id'=>$orderId,'admin_id'=>'','admin_name'=>'','text'=>"bonusListStr:$bonusListStr",'behavior'=>'test bonus','result'=>'success']);
                //给该微店发红包
                if($shopLevel > 0 && $shopLevel < 3){      //只有红人馆店和首席馆才会产生销售红包
                    $data = array(
                        'member_id'     =>$orderInfo['ms_id'],
                        'type'          =>2,
                        'price'         => $bonusList['own'],
                        'p_settle_time' =>'',
                        'releranceInfo'  =>array(
                            'order_id'=>$orderId,
                            'order_price'=>$cost,
                            'rebate_rate'=>$rule['self'],
                            'shop_name'=>$shopInfo['shop_name'],
                            'order_member_id'=>$orderInfo['member_id'],
                            'rec_member_id'     =>$orderInfo['ms_id'],
                            'is_self'=>1
                        )
                    );
                    $this->insertOneBonusDetail($data,'sales');

                    //给店主推送消息
                    $replaceArr = [
                        'subject'=>[
                            '{{titlePre}}'=>'您的店铺',
                            '{{shopName}}'=>''
                        ],
                        'message'=>[
                            '{{bonusDesc}}'=>($isSelfCostOrder) ? '补发' : '',
                            '{{price}}' =>round($data['price'],2)
                        ]
                    ];
                    //订单商品信息
                    $model = new OrderProductModel();
                    $productName = $model->where("order_id='$orderId'")->field("product_name")->find();

                    $productName = $productName['product_name'];
                    //用户昵称
                    $model = new MemberModel();
                    $userName = $model->where("userid=".$orderInfo['member_id'])->field('name')->find();

                    $userName = $userName['name'];
                    $param = [
                        'memberId'=>$orderInfo['ms_id'],
                        'keyword1'=>$this->config['money'].' '.$orderInfo['cost']."（实际参与提成金额:".$this->config['money']." ".round($data['releranceInfo']['order_price'],2)."）",
                        'keyword2'=>$productName,
                        'keyword3'=>$orderId,
                        'keyword4'=>$userName,
                        'url'=>'http://wx.52ywy.com/?shop='.$orderInfo['ms_id'].'#&shop/orderdetail/?id='.$orderId
                    ];
                    $Wxpush = new Wxpush();
                    $message = $Wxpush->getMessageDetail('shopOrderSuccess', $replaceArr, $param);
                    if(!empty($message)){//调用接口
                        $param['first'] = $message['subject'];
                        $param['remark'] = $message['message'];

                        //$result = Api::callItemApi('Weixin', 'msgPush', ["memberId"=>$param['memberId'],"msgType"=>$flag,"msgJson"=>json_encode($param)]);
                        $result = $Wxpush->msgPush($param['memberId'], 'shopOrderSuccess', $param);
                        //写日志
                        $data['param'] = ["memberId"=>$param['memberId'],"msgType"=>'shopOrderSuccess',"msgInfo"=>$param];
                        $data['result'] = $result;
                        $datas = json_encode($data,JSON_UNESCAPED_UNICODE);
                        $datas = @mysql_escape_string($datas);
                        $modes_log = new GeneralLogModel();
                        $modes_log->add(['type'=>'PUSH_WX_MSG','data'=>$datas,'status'=>1]);
                    }
                }

                switch ($shopLevel)
                {
                    case 1:
                        if($shopInfo['direct_rec_mid']>0){  //服务奖

                        }
                        break;
                    case 2:
                        $fMid = strstr($shopInfo['relations'],',',true);//上级首席馆的ID

                        //给该微店的上级首席馆发红包
                        $data = array(
                            'member_id'     =>$fMid,
                            'type'          =>2,
                            'price'         => $bonusList['hong_shop_1'],
                            'p_settle_time' =>'',
                            'releranceInfo'  =>array(
                                'order_id'=>$orderId,
                                'order_price'=>$cost,
                                'rebate_rate'=>$allRule['1']['self'] - $rule['self'],
                                'shop_name'=>$shopInfo['shop_name'],
                                'order_member_id'=>$orderInfo['member_id'],
                                'rec_member_id'     =>$orderInfo['ms_id'],
                                'is_self'=>0,
                                'isSelfCostOrder'=>$isSelfCostOrder,
                                'order_cost'=>$orderInfo['cost']
                            )
                        );
                        $this->insertOneBonusDetail($data,'sales');

                        if($fMid!=$shopInfo['direct_rec_mid']){//如果上级不是他的直接推荐人    服务奖

                        }
                        break;
                    case 3:
                        $fRate = 0;//首席馆返利比例系数
                        $fMid = strstr($shopInfo['relations'],',',true);//上级首席馆的ID
                        $tempRelations = str_replace(','.$fMid.',', '', ','.$shopInfo['relations']);
                        $sMid = strstr($tempRelations,',',true);//第二级店的ID

                        if($sMid == $orderInfo['ms_id']){//如果第二级店就是当前店
// 	                        $fRate = $allRule['1']['self'] - $rule['self'];
                            $fRate = $allRule['1']['self'] - $allRule['2']['self'];
                        }else{
                            $sql = "select level from ".TARENTO." where member_id={$sMid}";
                            $this->db->query($sql);
                            $sLevel = $this->db->fetchField('level');

                            if($sLevel == 2){
                                //给该微店的直接推荐人发红包
                                $data = array(
                                    'member_id'     =>$sMid,
                                    'type'          =>2,
                                    'price'         => $bonusList['shop_2'],
                                    'p_settle_time' =>'',
                                    'releranceInfo'  =>array(
                                        'order_id'=>$orderId,
                                        'order_price'=>$cost,
                                        'rebate_rate'=>$allRule['2']['self'] - $rule['self'],
                                        'shop_name'=>$shopInfo['shop_name'],
                                        'order_member_id'=>$orderInfo['member_id'],
                                        'rec_member_id'     =>$orderInfo['ms_id'],
                                        'is_self'=>0,
                                        'isSelfCostOrder'=>$isSelfCostOrder,
                                        'order_cost'=>$orderInfo['cost']
                                    )
                                );
                                $this->insertOneBonusDetail($data,'sales');
                            }
                            $fRate = $allRule['1']['self'] - $allRule['2']['self'];
                        }

                        //给该微店的上级首席馆发红包
                        $data = array(
                            'member_id'     =>$fMid,
                            'type'          =>2,
                            'price'         => $bonusList['shop_1'],
                            'p_settle_time' =>'',
                            'releranceInfo'  =>array(
                                'order_id'=>$orderId,
                                'order_price'=>$cost,
                                'rebate_rate'=>$fRate,
                                'shop_name'=>$shopInfo['shop_name'],
                                'order_member_id'=>$orderInfo['member_id'],
                                'rec_member_id'     =>$orderInfo['ms_id'],
                                'is_self'=>0,
                                'isSelfCostOrder'=>$isSelfCostOrder,
                                'order_cost'=>$orderInfo['cost']
                            )
                        );

                        $this->insertOneBonusDetail($data,'sales');

                        break;
                    default:
                        break;
                }

                return true;
            }
        }

        return false;
    }


    /**
     * 店铺升级
     * @param unknown $memberId
     * @param unknown $level 升级到什么级别
     * @param unknown $payInfo 支付信息
     */
    public function upgrade_shop($memberId,$level,$orderId=null,$payInfo = array(),$type = null){
        if($memberId>0){
            $model = new MicroShopModel();
            $shopInfo = $model->where("member_id=$memberId")->field("level")->find();

            //查询店铺是否可升级
            $tr_model = new TarentoModel();
            $tr_model->where("member_id=$memberId")->field("can_upgrade_shop,invite_code")->find();

            if(empty($canUpgrade['invite_code'])){
                $code = $tr_model->buildInviteCode($memberId);//邀请码
                $tr_model->where("member_id=$memberId")->save(['invite_code'=>$code]);
            }

            if(!empty($shopInfo) && $canUpgrade['can_upgrade_shop'] == 1){
                if($shopInfo['level']>$level){
                    //更新店铺等级
                    $model = new MicroShopModel();
                    $model->where("member_id=$memberId")->save(['level'=>$level]);
                    //更新树层级结构
                    $status = $this->change_tarento_tree($memberId, $level);

                    if(empty($type) || $type == null){
                        //返红包
                        $this->giveOutBonusOfRecShop($memberId,$orderId);
                    }


                    //写入支付日志
                    $payInfo['member_id'] = $memberId;
                    //$this->insertOnePayLog($payInfo);

                    return true;
                }
                return false;
            }

            return false;
        }

        return false;
    }


    public function arr2equation($array, $symbol = ',') {
        if(empty($array) || !is_array($array)) return false;

        $i = 0;
        $count = count($array);
        $equation = '';
        foreach ($array as $key => $value) {
            if ($count == $i) {
                $equation .= $key . '=' . $value;
            } else {
                $equation .= $key . '=' . $value . $symbol;
            }

            $i++;
        }

        return trim($equation, $symbol);
    }

    /**
     * 给推荐人发红包    -- 直接支付298
     * @param unknown $memberId 开店或升级店铺的用户ID
     */
    public function giveOutBonusOfRecShop($memberId,$orderId=null){
        if($memberId>0){
            $level_info = $this->where("member_id=$memberId")->field('level')->find();
            $level = $level_info['level'];
            if($level > 0 && $level < 3){     //只有红人馆店和首席馆才有推广奖
                $allCost = '';
                $product_id = '';
                if($orderId){
                    //查询当前购买产品ID
                    $orproModel = new OrderProductModel();
                    $ret_order_product = $orproModel->where("order_id=$orderId")->field("product_id,active_id")->select();
                    $productIDS = array();
                    foreach ($ret_order_product as $item_product) {
                        $productIDS[] = $item_product['product_id'];
                    }

                    //查询该用户累积消费金额
                    $orderModel = new OrderModel();
                    $re = $orderModel->where("status=2 and member_id=$memberId")->field("cost")->select();
                    foreach($re as $vos){
                        $allCost += $vos['cost'];
                    }
                }
                if(in_array(31679, $productIDS) || in_array(31680, $productIDS) || in_array(32146, $productIDS) || in_array(32145, $productIDS) || in_array(32144, $productIDS) || in_array(32143, $productIDS) || in_array(32142, $productIDS) || in_array(31951, $productIDS) || in_array(31950, $productIDS) || in_array(31949, $productIDS) || $allCost >= 1000){
                    $bonusInfos = $this->bonusRuleOfRecomendingShops[$level];

                    if(!empty($bonusInfos)){
                        $t_model = new TarentoModel();
                        $mInfo = $t_model->where("member_id=$memberId")->field("direct_rec_mid")->find();

                        //查询直接推荐人用户等级，只有红人才有推荐奖
                        $mInfos = $t_model->where("member_id=".$mInfo['direct_rec_mid'])->field("direct_rec_mid")->find();

                        if(!empty($mInfo)){
                            if($mInfo['direct_rec_mid']>0  && $mInfos['level'] == 2){
                                //直接推荐人
                                $data = array(
                                    'member_id'     =>$mInfo['direct_rec_mid'],
                                    'type'          =>1,
                                    'price'         =>$bonusInfos['direct'],
                                    'p_settle_time' =>date('Y-m-d H:i:s'),
                                    'releranceInfo'  =>array(
                                        'rec_member_id'=>$memberId,
                                        'shop_relation'=>1,
                                        'shop_level'=>$level,
                                    )
                                );
                                $this->insertOneBonusDetail($data,'expand');
                            }

                            $sql = "select direct_rec_mid,level from ".TARENTO." where member_id={$mInfos['direct_rec_mid']}";
                            $this->db->query($sql);
                            $mInfoss = $this->db->fetchRow();

                            if($mInfos['direct_rec_mid']>0 && $mInfoss['level'] == 2){
                                //给上级直接推荐人发红包，且必须是红人
                                $data = array(
                                    'member_id'     =>$mInfos['direct_rec_mid'],
                                    'type'          =>1,
                                    'price'         =>$bonusInfos['indirect'],
                                    'p_settle_time' =>date('Y-m-d H:i:s'),
                                    'releranceInfo'  =>array(
                                        'rec_member_id'=>$memberId,
                                        'shop_relation'=>2,
                                        'shop_level'=>$level,
                                    )
                                );
                                $this->insertOneBonusDetail($data,'expand');
                            }

                            return true;
                        }
                    }



                }else{
                    $bonusInfo = $this->bonusRuleOfRecomendingShop[$level];

                    if(!empty($bonusInfo)){
                        $sql = "select direct_rec_mid,indirect_rec_mid,level from ".TARENTO." where member_id={$memberId}";
                        $this->db->query($sql);
                        $mInfo = $this->db->fetchRow();

                        if(!empty($mInfo)){
                            if($mInfo['direct_rec_mid']>0){
                                //直接推荐人
                                $data = array(
                                    'member_id'     =>$mInfo['direct_rec_mid'],
                                    'type'          =>1,
                                    'price'         =>$bonusInfo['direct'],
                                    'p_settle_time' =>date('Y-m-d H:i:s'),
                                    'releranceInfo'  =>array(
                                        'rec_member_id'=>$memberId,
                                        'shop_relation'=>1,
                                        'shop_level'=>$level,
                                    )
                                );
                                $this->insertOneBonusDetail($data,'expand');
                            }

                            if($mInfo['indirect_rec_mid']>0){
                                //间接推荐人
                                $data = array(
                                    'member_id'     =>$mInfo['indirect_rec_mid'],
                                    'type'          =>1,
                                    'price'         =>$bonusInfo['indirect'],
                                    'p_settle_time' =>date('Y-m-d H:i:s'),
                                    'releranceInfo'  =>array(
                                        'rec_member_id'=>$memberId,
                                        'shop_relation'=>2,
                                        'shop_level'=>$level,
                                    )
                                );
                                $this->insertOneBonusDetail($data,'expand');
                            }

                            return true;
                        }
                    }
                }



            }
        }

        return false;
    }

    /**
     * 写入一个红包
     * @param unknown $data
     * @param unknown $type 推广'expand',销售'sales',服务'service',订单任务'task_count',推广任务'task_expand'
     */
    public function insertOneBonusDetail($data,$type){
        if(!empty($data) && !empty($type)){
            //写入红包详情表
            $bonusStatus = 0;
            $relation_ms_id = $data['releranceInfo']['rec_member_id'] ? $data['releranceInfo']['rec_member_id'] : 0;
            $service_ms_id = isset($data['releranceInfo']['service_ms_id']) ? $data['releranceInfo']['service_ms_id'] : 0;
            if(in_array($type, array('sales','service'))){
                $bonusStatus = -1;
            }
            $model = new MicroShopBonusDetailModel();
            $bonusId = $model->add(['member_id'=>$data['member_id'],'type'=>$data['type'],'price'=>$data['price'],'p_settle_time'=>$data['p_settle_time'],'status'=>$bonusStatus,'relation_ms_id'=>$relation_ms_id]);

            if($bonusId>0){
                if($type == 'sales' && $data['releranceInfo']['is_self'] == 0){
                    $orderId = $data['releranceInfo']['order_id'];
                    //给店主推送消息
                    $replaceArr = [
                        'subject'=>[
                            '{{titlePre}}'=>'您推广的店铺',
                            '{{shopName}}'=>$data['releranceInfo']['shop_name']
                        ],
                        'message'=>[
                            '{{bonusDesc}}'=>$data['releranceInfo']['isSelfCostOrder'] ? '补发' : '',
                            '{{price}}' =>round($data['price'],2)
                        ]
                    ];
                    //订单商品信息
                    $p_model = new OrderProductModel();
                    $productName = $p_model->where("order_id=$orderId")->field("product_name")->find();
                    $productName = $productName['product_name'];
                    //用户昵称
                    $m_model = new MemberModel();
                    $userName = $m_model->where("userid=".$data['releranceInfo']['order_member_id'])->field("name")->find();
                    $userName = $userName['name'];

                    $param = [
                        'memberId'=>$data['member_id'],
                        'keyword1'=>$this->config['money'].' '.$data['releranceInfo']['order_cost']."（实际参与提成金额:".$this->config['money']." ".round($data['releranceInfo']['order_price'],2)."）",
                        'keyword2'=>$productName,
                        'keyword3'=>$orderId,
                        'keyword4'=>$userName,
                        'url'=>'http://wx.52ywy.com/?shop='.$data['member_id'].'#&shop/orderdetail/?id='.$orderId
                    ];
                    $Wxpush = new Wxpush();
                    $message = $Wxpush->getMessageDetail('shopOrderSuccess', $replaceArr, $param);
                    if(!empty($message)){//调用接口
                        $param['first'] = $message['subject'];
                        $param['remark'] = $message['message'];
                        $result = $Wxpush->msgPush($param['memberId'], 'shopOrderSuccess', $param);
                        //写日志
                        $data['param'] = ["memberId"=>$param['memberId'],"msgType"=>'shopOrderSuccess',"msgInfo"=>$param];
                        $data['result'] = $result;
                        $datas = json_encode($data,JSON_UNESCAPED_UNICODE);
                        $datas = @mysql_escape_string($datas);
                        $modes_log = new GeneralLogModel();
                        $modes_log->add(['type'=>'PUSH_WX_MSG','data'=>$datas,'status'=>1]);
                    }

                }
                if($type == 'expand'){
                    $microShopModel = new MicroShopModel();
                    $shopInfo = $microShopModel->where("member_id=".$data['member_id'])->find();
//     	            //给用户推送消息
                    $replaceArr = [];
                    $param = [
                        'memberId'=>$data['member_id'],
                        'keyword1'=>$shopInfo['name'],
                        'keyword2'=>$data['price'] ."元",
                        'keyword3'=>date("YmdHis"),
                        'url'     =>'http://wx.52ywy.com/?shop='.$data['member_id'].'#&shop/generalize/?type='.$data['type']
                    ];
                    $Wxpush = new Wxpush();
                    $message = $Wxpush->getMessageDetail('tuijianSuccess', $replaceArr, $param);
                    if(!empty($message)){//调用接口
                        $param['first'] = $message['subject'];
                        $param['remark'] = $message['message'];
                        $result = $Wxpush->msgPush($param['memberId'], 'tuijianSuccess', $param);
                        //写日志
                        $data['param'] = ["memberId"=>$param['memberId'],"msgType"=>'tuijianSuccess',"msgInfo"=>$param];
                        $data['result'] = $result;
                        $datas = json_encode($data,JSON_UNESCAPED_UNICODE);
                        $datas = @mysql_escape_string($datas);
                        $modes_log = new GeneralLogModel();
                        $modes_log->add(['type'=>'PUSH_WX_MSG','data'=>$datas,'status'=>1]);
                    }
                }


                //写红包其他相关表
                switch ($type)
                {
                    case 'expand':    //推广获得奖励
                        $model = new MicroShopBonusExpandModel();
                        $model->add(['bonus_id'=>$bonusId,'rec_member_id'=>$data['releranceInfo']['rec_member_id'],'shop_relation'=>$data['releranceInfo']['shop_relation'],'shop_level'=>$data['releranceInfo']['shop_level']]);
                        break;
                    case 'sales':    //销售获得奖励
                        $model = new MicroShopBonusSalesModel();
                        $model->add(['bonus_id'=>$bonusId,'order_id'=>$data['releranceInfo']['order_id'],'order_price'=>$data['releranceInfo']['order_price'],'rebate_rate'=>$data['releranceInfo']['rebate_rate']]);
                        break;
                    case 'service':  //服务获得奖励
                        $model = new MicroShopBonusServiceModel();
                        $model->add(['bonus_id'=>$bonusId,'order_id'=>$data['releranceInfo']['order_id'],'order_price'=>$data['releranceInfo']['order_price'],'rebate_rate'=>$data['releranceInfo']['rebate_rate'],'service_ms_id'=>$service_ms_id]);
                        break;
                    case 'task_count':
                        $model = new MicroShopBonusTaskCountModel();
                        $model->add(['bonus_id'=>$bonusId,'order_amount'=>$data['releranceInfo']['order_amount'],'rebate'=>$data['releranceInfo']['rebate']]);
                        break;
                    case 'task_expand':
                        $model = new MicroShopBonusTaskExpandModel();
                        $model->add(['bonus_id'=>$bonusId,'expand_shop_number'=>$data['releranceInfo']['expand_shop_number']]);
                        break;
                    default:
                        break;
                }

                return true;
            }
        }

        return false;
    }

    /**
     * 改变树结构
     * @param unknown $memberId
     * @param unknown $level
     */
    public function change_tarento_tree($memberId,$level){
        $model = new TarentoModel();
        $memInfo = $model->where("member_id=$memberId")->field("direct_rec_mid,indirect_rec_mid,relations,level,have_discount_price")->find();

        if(!empty($memInfo)){
            if($memInfo['level']==1){//已经是首席馆不改变
                return false;
            }
            if($memInfo['level']>=$level){
                $shopLevel = "";
                $resStatus = false;
                $relationsPre = str_replace(','.$memberId.',', '', $memInfo['relations']).",";//升级之前 上一级的relations
                $recMemInfo = $this->getMemberRecMemInfo($memberId,$memInfo, $level);
                switch ($level)
                {
                    case 1://升级为首席馆
                        $shopLevel = "首席馆";
                        //更新该用户
                        $sql = "update haiou_tarento set direct_rec_mid='".$recMemInfo['direct_rec_mid']."',indirect_rec_mid='".$recMemInfo['indirect_rec_mid']."',relations='".$recMemInfo['relations']."',level=1 where member_id=$memberId";
                        $model->query($sql);

                        //更新该用户下级的relations和level
//     	                $num = $memInfo['level']-2;//计算下级level的系数
                        $sql = "update haiou_tarento set relations=REPLACE(relations,'$relationsPre','') where relations like '".$memInfo['relations']."_%'";
                        $model->query($sql);

                        //更新该用户下级的间接推荐人
                        $sql = "update haiou_tarento set indirect_rec_mid='".$recMemInfo['direct_rec_mid']."' where relations like '".$memInfo['relations']."_%' and level=3";
                        $model->query($sql);//更新直接下一级

                        if($memInfo['level']==2){//如果升级之前是红人馆，则与他推广的红人馆断开推荐关系

                            $expandShops = $model->where("direct_rec_mid=$memberId and level=2")->field("member_id,relations")->select();
                            if(!empty($expandShops)){
                                foreach ($expandShops as $exv)
                                {
                                    $fMid = strstr($exv['relations'], ',', true);//顶级首席馆ID
                                    if($fMid>0){
                                        $model = new TarentoModel();
                                        $model->where("member_id=$fMid")->field("direct_rec_mid")->find();

                                        $fdrmid = $model->where("member_id=$fMid")->field("direct_rec_mid")->find();
                                        $fdrmid = $fdrmid['direct_rec_mid'];//首席馆的直接推荐人

                                        //更新
                                        $model->where("member_id=".$exv['member_id'])->save(['direct_rec_mid'=>$fMid,'indirect_rec_mid'=>$fdrmid]);
                                    }
                                }
                            }
                        }

                        //=========发优惠券=========
                        //获取是否需要返红包   发放优惠券
//     	                $needStatus = $this->canOrNotGiveBonusAndCoupons($level, $memInfo['have_discount_price']);
//     	                if($needStatus){
//         	                include_once($this->config["webroot"]."/module/micro_shop/includes/plugin_coupons_class.php");
//         	                $couponsObj = new Coupons();
//         	                $couponsObj->createOnePackage($memberId, 1);    //发放优惠券
//     	                }
                        //=======================

                        $resStatus = true;

                        //给店主推送消息
                        $replaceArr = [
                            'subject'=>[
                                '{{shopLevel}}'=>$shopLevel
                            ]
                        ];
                        $shopName = $this->where("member_id=$memberId")->field("name")->find();
                        $shopName = $shopName['name'];
                        $param = [
                            'memberId'=>$memberId,
                            'keyword1'=>$shopName,
                            'keyword2'=>date('Y-m-d H:i:s'),
                            'url'     =>'http://wx.52ywy.com'
                        ];
                        $Wxpush = new Wxpush();
                        $message = $Wxpush->getMessageDetail('shopUpgradeSuccess', $replaceArr, $param);

                        if(!empty($message)){//调用接口
                            $param['first'] = $message['subject'];
                            $param['remark'] = $message['message'];

                            //$result = Api::callItemApi('Weixin', 'msgPush', ["memberId"=>$param['memberId'],"msgType"=>$flag,"msgJson"=>json_encode($param)]);

                            $result = $Wxpush->msgPush($param['memberId'], 'shopUpgradeSuccess', $param);
                            //写日志
                            $data['param'] = ["memberId"=>$param['memberId'],"msgType"=>'shopUpgradeSuccess',"msgInfo"=>$param];
                            $data['result'] = $result;
                            $datas = json_encode($data,JSON_UNESCAPED_UNICODE);
                            $datas = @mysql_escape_string($datas);
                            $modes_log = new GeneralLogModel();
                            $modes_log->add(['type'=>'PUSH_WX_MSG','data'=>$datas,'status'=>1]);
                        }

                        break;
                    case 2://升级为红人馆
                        $shopLevel = "红人馆";
                        //更新该用户
                        $model->where("member_id=$memberId")->save(['direct_rec_mid'=>$recMemInfo['direct_rec_mid'],'indirect_rec_mid'=>$recMemInfo['indirect_rec_mid']]);

                        //更新该用户下级的relations和level
//     	                $num = $memInfo['level']-2;//计算下级level的系数
                        $fMid = strstr($relationsPre, ',', true);//顶级首席馆ID
                        $sql = "update haiou_tarento set relations=REPLACE(relations,'$relationsPre','$fMid,') where relations like '".$memInfo['relations']."_%'";
                        $model->query($sql);

                        //更新该用户下级的间接推荐人//更新直接下一级
                        $model->where("relations like '".$memInfo['relations']."_%' and level=3")->save(['indirect_rec_mid'=>$recMemInfo['direct_rec_mid']]);

                        $resStatus = true;

                        //给店主推送消息
                        $replaceArr = [
                            'subject'=>[
                                '{{shopLevel}}'=>$shopLevel
                            ]
                        ];

                        $shopName = $this->where("member_id=$memberId")->field("name")->find();
                        $shopName = $shopName['name'];
                        $param = [
                            'memberId'=>$memberId,
                            'keyword1'=>$shopName,
                            'keyword2'=>date('Y-m-d H:i:s'),
                            'url'     =>'http://wx.52ywy.com'
                        ];
                        $Wxpush = new Wxpush();
                        $message = $Wxpush->getMessageDetail('shopUpgradeSuccess', $replaceArr, $param);

                        if(!empty($message)){//调用接口
                            $param['first'] = $message['subject'];
                            $param['remark'] = $message['message'];

                            //$result = Api::callItemApi('Weixin', 'msgPush', ["memberId"=>$param['memberId'],"msgType"=>$flag,"msgJson"=>json_encode($param)]);

                            $result = $Wxpush->msgPush($param['memberId'], 'shopUpgradeSuccess', $param);
                            //写日志
                            $data['param'] = ["memberId"=>$param['memberId'],"msgType"=>'shopUpgradeSuccess',"msgInfo"=>$param];
                            $data['result'] = $result;
                            $datas = json_encode($data,JSON_UNESCAPED_UNICODE);
                            $datas = @mysql_escape_string($datas);
                            $modes_log = new GeneralLogModel();
                            $modes_log->add(['type'=>'PUSH_WX_MSG','data'=>$datas,'status'=>1]);
                        }
                        break;
                    case 3://开店
                        $shopLevel = "吃货";
                        $levelTemp = $model->where("member_id=".$recMemInfo['direct_rec_mid'])->field("level")->find();
                        $levelTemp = $levelTemp['level'];
                        //更新该用户
                        $model->where("member_id=$memberId")->save(['direct_rec_mid'=>$recMemInfo['direct_rec_mid'],'indirect_rec_mid'=>$recMemInfo['indirect_rec_mid'],'relations'=>$recMemInfo['relations'],'level'=>3]);
                        //更新该用户下级的relations
                        $sql = "update haiou_tarento set relations=REPLACE(relations,'".$memInfo['relations']."','".$recMemInfo['relations']."') where relations like '".$memInfo['relations']."_%'";
                        $model->query($sql);

                        //更新该用户下级的间接推荐人
                       //更新直接下一级
                        $model->where("relations like '".$recMemInfo['relations']."_%'")->save(['indirect_rec_mid'=>$recMemInfo['direct_rec_mid']]);

                        //查询上级是否为吃货，是则统计上级吃货直接推广的吃货数量（获得免费升级红人馆资格）
                        $bossIdStr = ','.str_replace(','.$memberId.',', '', $memInfo['relations']);
                        $bossMid = substr($bossIdStr, strrpos($bossIdStr,','));//上级店铺ID
                        $bossMid = trim($bossMid,',');
                        if($bossMid>0){
                            $bossInfo = $model->where("member_id=$bossMid")->find();
                            if(!empty($bossInfo) && $bossInfo['level']>=3 && $bossInfo['have_discount_price']!=3){
                                $level1 = $bossInfo['level']+1;
                                $shopNum = $model->where("relations like '".$bossInfo['relations']."_%' and level=$level1 and have_micro_shop=1")->field("count(*) as shopNum")->find();
                                $shopNum = $shopNum['shopNum'];
                                if($shopNum == $this->ruleOfUpgradeShopFree['2']['num']){//获得免费升级红人馆资格

                                    $model->where("member_id=$bossMid")->save(['have_discount_price'=>3]);
                                }
                            }
                        }

                        //发红包
//     	                $this->giveOutBonusOfRecShop($memberId);

                        //================发优惠券=============
                        //获取是否需要返红包   发放优惠券
//     	                $needStatus = $this->canOrNotGiveBonusAndCoupons($level, $memInfo['have_discount_price']);
//     	                if($needStatus){
//     	                    include_once($this->config["webroot"]."/module/micro_shop/includes/plugin_coupons_class.php");
//     	                    $couponsObj = new Coupons();
//     	                    $couponsObj->createOnePackage($memberId, 3);
//     	                }
                        //=========================

                        $resStatus = true;

                        //给店主推送消息
                        $replaceArr = [];

                        $shopName = $this->where("member_id=$memberId")->field("name")->find();
                        $shopName = $shopName['name'];
                        $param = [
                            'memberId'=>$memberId,
                            'keyword1'=>$shopName,
                            'keyword2'=>date('Y-m-d H:i:s'),
                            'url'     =>'http://wx.52ywy.com'
                        ];
                        $Wxpush = new Wxpush();
                        $message = $Wxpush->getMessageDetail('openShopSuccess', $replaceArr, $param);

                        if(!empty($message)){//调用接口
                            $param['first'] = $message['subject'];
                            $param['remark'] = $message['message'];

                            //$result = Api::callItemApi('Weixin', 'msgPush', ["memberId"=>$param['memberId'],"msgType"=>$flag,"msgJson"=>json_encode($param)]);

                            $result = $Wxpush->msgPush($param['memberId'], 'openShopSuccess', $param);
                            //写日志
                            $data['param'] = ["memberId"=>$param['memberId'],"msgType"=>'openShopSuccess',"msgInfo"=>$param];
                            $data['result'] = $result;
                            $datas = json_encode($data,JSON_UNESCAPED_UNICODE);
                            $datas = @mysql_escape_string($datas);
                            $modes_log = new GeneralLogModel();
                            $modes_log->add(['type'=>'PUSH_WX_MSG','data'=>$datas,'status'=>1]);
                        }

                        break;
                    default:
                        break;
                }

                //给上级店主推送消息
                $replaceArr = [
                    'subject'=>[
                        '{{shopLevel}}'=>$shopLevel
                    ]
                ];
                $memNewInfo = $model->where("meber_id=$memberId")->field("direct_rec_mid")->find();

                $shopName = $this->where("member_id=$memberId")->field("name")->find();
                $shopName = $shopName['name'];
                $param = [
                    'memberId'=>$memNewInfo['direct_rec_mid'],
                    'keyword1'=>$shopName,
                    'keyword2'=>date('Y-m-d H:i:s'),
                    'url'     =>'http://wx.52ywy.com/?shop='.$memNewInfo['direct_rec_mid'].'#&shop/fendian'
                ];
                $Wxpush = new Wxpush();
                $message = $Wxpush->getMessageDetail('openShopSuccess', $replaceArr, $param);

                if(!empty($message)){//调用接口
                    $param['first'] = $message['subject'];
                    $param['remark'] = $message['message'];

                    //$result = Api::callItemApi('Weixin', 'msgPush', ["memberId"=>$param['memberId'],"msgType"=>$flag,"msgJson"=>json_encode($param)]);

                    $result = $Wxpush->msgPush($param['memberId'], 'openShopSuccess', $param);
                    //写日志
                    $data['param'] = ["memberId"=>$param['memberId'],"msgType"=>'openShopSuccess',"msgInfo"=>$param];
                    $data['result'] = $result;
                    $datas = json_encode($data,JSON_UNESCAPED_UNICODE);
                    $datas = @mysql_escape_string($datas);
                    $modes_log = new GeneralLogModel();
                    $modes_log->add(['type'=>'PUSH_WX_MSG','data'=>$datas,'status'=>1]);
                }

               // return ['code'=>1122,'msg'=>'未找到消息模板，推送消息为空'];

               // Helper::pushMessage('openShopSuccess', $replaceArr, $param);

                return $resStatus;
            }
        }
        return false;
    }

    /**
     * 获取升级后直接推荐人和间接推荐人ID和relations
     * @param unknown $meberInfo
     * @param unknown $level
     */
    private function getMemberRecMemInfo($memberId,$meberInfo,$level){
        $dmid = 0;//直接推荐人ID
        $indmid = 0;//间接推荐人ID
        $relations = '';
        if(!empty($meberInfo)){
            if($meberInfo['direct_rec_mid']>0 && $meberInfo['direct_rec_mid']!=$this->officialMemberId){
                $model = new TarentoModel();
                $directMemInfo = $model->where("member_id=$memberId")->field("direct_rec_mid,indirect_rec_mid,level")->find();
                $directMemlevel = $directMemInfo['level'];

                switch ($level){
                    case 1:
                        if($directMemlevel==1){
                            $dmid = $meberInfo['direct_rec_mid'];
                            $indmid = $directMemInfo['direct_rec_mid'];
                        }else{
                            $dmid = strstr($meberInfo['relations'],',',true);
                            $indmid = $model->where("member_id=$dmid")->field("direct_rec_mid")->find();
                            $indmid = $indmid['direct_rec_mid'];
                        }

                        $relations = $memberId.",";
                        break;
                    case 2:
                        if($directMemlevel==1){
                            $dmid = $meberInfo['direct_rec_mid'];
                            $indmid = $directMemInfo['direct_rec_mid'];
                            $relations = $meberInfo['direct_rec_mid'].",".$memberId.",";
                        }elseif($directMemlevel==2){
                            $fMid = strstr($meberInfo['relations'],',',true);//顶级首席馆的ID

                            $dmid = $meberInfo['direct_rec_mid'];
                            $indmid = $directMemInfo['direct_rec_mid'];
                            $relations = $fMid.",".$memberId.",";
                        }else{
                            $fMid = strstr($meberInfo['relations'],',',true);//顶级首席馆的ID
                            $tempRelations = str_replace(','.$fMid.',', '', ','.$meberInfo['relations']);
                            $sMid = strstr($tempRelations,',',true);//第二级店的ID

                            $sMInfo = $model->where("member_id=$sMid")->field("direct_rec_mid")->find();
                            if($sMInfo['level']==2){
                                $dmid = $sMid;
                                $indmid = $sMInfo['direct_rec_mid'];
                            }else{
                                $dmid = $fMid;
                                $indmid = $model->where("member_id=$dmid")->field("direct_rec_mid")->find();
                                $indmid = $indmid['direct_rec_mid'];
                            }

                            $relations = $fMid.",".$memberId.",";
                        }
                        break;
                    case 3://开店
                        if($directMemlevel>=3){
                            $directShopInfo = $this->where("member_id=".$meberInfo['direct_rec_mid'])->field("member_id")->find();
                            if(empty($directShopInfo)){//直接推荐人没开店
                                //把树上所有人的开店情况查出来
                                $memIds = str_replace(','.$memberId.',', '', $meberInfo['relations']);
                                $memIdArr = explode(',', $memIds);
                                $memTemp = $this->where("member_id in ($memIds)")->field("member_id,level")->select();
                                $memArr = array();
                                foreach ($memTemp as $val)
                                {
                                    $memArr[$val['member_id']] = $val['level'];
                                }
                                $relationsTemp = "";
                                $preMemId = 0;
                                foreach ($memIdArr as $mid)
                                {
                                    if(empty($memArr[$mid])){
                                        break;
                                    }

                                    $preMemId = $mid;
                                    $relationsTemp .= $mid.",";
                                }

                                $dmid = $preMemId;

                                $indmid = $model->where("member_id=$dmid")->field("direct_rec_mid")->find();
                                $indmid = $indmid['direct_rec_mid'];
                                $relations = $relationsTemp.$memberId.",";
                            }else{
                                $dmid = $meberInfo['direct_rec_mid'];
                                $indmid = $meberInfo['indirect_rec_mid'];
                                $relations = $meberInfo['relations'];
                            }
                        }else{
                            $dmid = $meberInfo['direct_rec_mid'];
                            $indmid = $meberInfo['indirect_rec_mid'];
                            $relations = $meberInfo['relations'];
                        }
                        break;
                    default:
                        $dmid = $meberInfo['direct_rec_mid'];
                        $indmid = $meberInfo['indirect_rec_mid'];
                        break;
                }
            }else{
                $dmid = $this->officialMemberId;
                if($level==1){
                    $relations = $memberId.",";
                }else{
                    $relations = $this->officialMemberId.",".$memberId.",";
                }
            }
        }

        return array('direct_rec_mid'=>$dmid,'indirect_rec_mid'=>$indmid,'relations'=>$relations);
    }

    /**
     * 计算各类奖励
     * 根据产品活动类型，以及用户的等级
     *
     * @author akiler
     * @since 20160621
     * @param $orderInfo
     * @param $orderProductList
     * @param $shopLevel
     * @return array
     */
    public function calculateKindsOfBonus($orderInfo, $orderProductList, $shopLevel){
        // 如果是第二单，则按照普通区进行分红
        $model = new QuanfanModel();
        $activeOrder = $model->where("member_id=".$orderInfo['member_id'])->field("COUNT(id) AS num_fan")->find();

        $data = array();

        // 按照活动类型分组，普通区active_id为0；
        foreach ($orderProductList as $item_product) {
            // 如果已经购买，则都是普通区产品
            if($activeOrder['num_fan'] > 0){
                $item_product['active_id'] = 0;
            }
            $data[$item_product['active_id']][] = $item_product;
        }

        $orderMinus = $orderInfo['cpns_price'] + $orderInfo['discount'] - $orderInfo['ms_discount'];

        $calcData = array();

        // 计算每组的商品消费金额
        foreach ($data as $key_d => $item_d) {
            $calcData[$key_d] = 0;
            foreach ($item_d as $item_d_pro) {
                $calcData[$key_d] += $item_d_pro['price'] * $item_d_pro['num'];
            }
        }

        $numCalc = count($calcData);
        $sumCalc = array_sum($calcData);
        $countCalc = 1;
        $sumRate = 0;

        // 扣除每组中的代金券，打折数据
        foreach ($calcData as $key_calc => $item_calc) {
            if($countCalc < $numCalc){
                // 按比例扣除
                $rate = ceil(($item_calc/$sumCalc) * $orderMinus);
                $calcData[$key_calc] -= $rate;
                $sumRate += $rate;
            }else{
                // 最后一个
                $calcData[$key_calc] -= $orderMinus - $sumRate;
            }

            $countCalc++;
        }

        // 计算各类奖励
        $bonusData = array(
            'own'   		=> 0,
            'hong_shop_1'   => 0,
            'shop_1'        => 0,
            'shop_2'        => 0
        );

        foreach ($calcData as $key_calc => $item_calc) {
            $allRule = $this->bonusRuleOfAll[$key_calc];
            $rule = $this->bonusRuleOfAll[$key_calc][$shopLevel];

            // 如果是吃货以上等级的用户购买，则自己也可以拿分红
            if(floatval($item_calc)<0){
                $item_calc = 1;
            }
            $bonusData['own'] += $item_calc * $rule['self'];

            // 红人购买，首席分红
            $shopLevel == 2 && $bonusData['hong_shop_1'] += $item_calc * ($allRule['1']['self'] - $rule['self']);

            // 吃货购买，红人、首席都能分红
            // 首席分红
            $shopLevel > 2 && $bonusData['shop_1'] += $item_calc * ($allRule['1']['self'] - $allRule['2']['self']);
            // 红人分红
            $shopLevel > 2 && $bonusData['shop_2'] += $item_calc * ($allRule['2']['self'] - $rule['self']);
        }

        return $bonusData;
    }

    /**
     * 等级LOGO拼接
     * @var string
     */
    public static $levelLogo = 'http://wx.52ywy.com/images/other/micro_shop/level/%d.png';

    /**
     * 默认店铺头像
     * @var string
     */
    public static $defaultShopLogo = 'http://wx.52ywy.com/images/other/logo.png';

    /**
     * 默认个人二维码
     * @var string
     */
    public static $defaultPersonalQrcode = 'http://wx.52ywy.com/images/other/default_personal_qrcode.jpg';


    /**
     * 获取微店信息
     * @param integer $memberId
     * @param array $isValid 状态是否只取有效的
     */
    public function getInfoById($memberId){
        $fields = ['member_id','name','description','personal_qrcode','level','logo','create_time', 'status', 'user_idcard'];

        $shop = $this->where("member_id=$memberId and status>0")->field($fields)->find();

        if(!empty($shop)){
            $shop['user_idcard'] = substr_replace($shop['user_idcard'], '******', 4, 8);
            $shop['levelLogo'] = sprintf(self::$levelLogo, $shop['level']);
            if (empty($shop['logo'])) {
                $shop['logo'] = self::$defaultShopLogo;
            }
        }
        //查询旗舰店邀请码
        $model = new TarentoModel();
        $inviteCode = $model->where("member_id=$memberId")->find();
        $shop['inviteCode'] = $inviteCode['invite_code'];
        return $shop;
    }

    /**
     * 获取微店信息
     * @param array $shopsId
     * @param array $isValid 状态是否只取有效的
     */
    public function getInfoByIds($shopsId){
        $fields = ['member_id', 'name', 'level','personal_qrcode', 'logo', 'create_time'];
        $shp_id = join(',',$shopsId);
        $shops = $this->where("member_id in ($shp_id)")->field($fields)->select();

        if(!empty($shops)){
            foreach ($shops as $shop) {
                $shop['levelLogo'] = sprintf(self::$levelLogo, $shop['level']);
                if (empty($shop['logo'])) {
                    $shop['logo'] = self::$defaultShopLogo;
                }
                empty($shop['personal_qrcode']) && $shop['personal_qrcode'] = self::$defaultPersonalQrcode;
            }
        }

        return $shops;
    }

}